import { PayloadAction, createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { AsyncState, ListState } from '..'
import { Favorite, apiDeleteFavorite, apiGetFavoriteList, apiPostFavorite, apiPutFavorite } from '../../api/favorite'

type FavoriteState = AsyncState & Omit<ListState<Favorite>, 'pager'> & {
    current: number
}
const initialState: FavoriteState = {
    status: 'idle',
    error: null,
    list: [],
    current: 0
}

export const fetchFavorites = createAsyncThunk('favorite/fetchFavorites', apiGetFavoriteList)
export const createFavorite = createAsyncThunk('favorite/createFavorite', apiPostFavorite)
export const updateFavorite = createAsyncThunk('favorite/updateFavorite', apiPutFavorite)
export const deleteFavorite = createAsyncThunk('favorite/deleteFavorite', apiDeleteFavorite)
export const favoriteSlice = createSlice({
    name: 'favorite',
    initialState: initialState,
    reducers: {
        favoriteIdChange(state, action: PayloadAction<number|null>) {
            if (action.payload) {
                state.current = action.payload
            }
            else{
                state.current =  0
            }
        }
    },
    extraReducers(builder) {
        builder
            .addCase(fetchFavorites.pending, (state) => {
                state.status = 'loading'
            })
            .addCase(fetchFavorites.fulfilled, (state, action) => {
                state.status = 'succeeded'
                state.list = action.payload.list
            })
            .addCase(fetchFavorites.rejected, (state) => {
                state.status = 'failed'
                state.error = '获取收藏夹列表失败'
            })
            .addCase(createFavorite.fulfilled, (state) => {
                state.status = 'idle'
            })
            .addCase(updateFavorite.fulfilled, (state) => {
                state.status = 'idle'
            })
            .addCase(deleteFavorite.fulfilled, (state) => {
                state.status = 'idle'
            })
    }
})
export const { favoriteIdChange } = favoriteSlice.actions
export default favoriteSlice.reducer